package leetcode.datastructures.stack;

import java.util.Scanner;

/**
 * @author shilei
 * @create 2021-11-08 19:
 * 栈的演示
 * 实现栈的思路分析
 *  1、使用数组来模拟栈
 *  2、定义一个 top 来表示栈顶，初始化为-1
 *  3、入栈 的操作，当有数据加入到栈时 top++ stack[top] = data
 *  4、出栈 的操作 int  value =stack[top] top-- return value
 */
public class ArrayStackDemo {

    public static void main(String[] args) {
        ArrayStack arrayStack = new ArrayStack(5);
        boolean loop = true;
        String key = "";
        Scanner scanner = new Scanner(System.in);
        while (loop) {
            System.out.println("show: 显示栈");
            System.out.println("push: 入栈");
            System.out.println("pop: 出栈");
            System.out.println("exit: 结束");
            System.out.println("请输入你的选择:");
            key = scanner.next();
            switch (key) {
                case "show":
                    arrayStack.forEachStack();
                    break;
                case "push":
                    System.out.println("请输入一个数：");
                    int data = scanner.nextInt();
                    arrayStack.pushStack(data);
                    break;
                case "pop":
                    int info = arrayStack.popStack();
                    System.out.println("data is: " +info);
                    break;
                case "exit":
                    scanner.close();
                    loop = false;
                    break;
            }
        }
        System.out.println("程序退出~");
    }
}

//定义一个 ArrayStack 表示栈
class ArrayStack{
    private int maxSize;//表示栈的大小
    private int[] stack;//表示栈 存储数据
    private int top = -1;//表示栈顶 默认-1

    public ArrayStack(int maxSize) {
        this.maxSize = maxSize;
        stack = new int [maxSize];
    }

    //判断栈满
    public boolean isFull(){
        return maxSize - 1 == top;
    }
    //判断栈空
    public boolean isEmpty(){
        return top == -1;
    }
    //入栈
    public void pushStack(int data){
        //判断是否栈满
        if (isFull()) {
            return;
        }
        top ++;
        stack[top] = data;
    }

    //出栈
    public int popStack() {
        //判断栈空
        if (isEmpty()) {
            System.out.println("栈空");
        }

        if (top > 0) {
            int empValue = stack[top];
            top --;
            return empValue;
        }
        return 0;
    }
    //显示栈 需要先从栈顶显示数据
    public void forEachStack(){
        if (isEmpty()) {
            System.out.println("栈空");
        }
        for (int i = top; i >= 0; i--) {
            System.out.printf("stack[%d] is:%d \n",i,stack[i]);
        }
    }
}
